<?php  
namespace Api\Controller;
use Api\Controller\BaseController;
use Org\Util\Easemob;
header("Content-Type: text/html;charset=utf-8"); 
class AroundController extends  BaseController {
private $uid;
	private $noCheck = array();
	private $Easemob;
	function _initialize() {
		parent::_initialize();
		//$token = I('post.token');
		$token = I('token');
		if($token){
			$user = M('user')->where(['cid'=>$token])->find();
			if(empty($user)){
				$user = M('token')->where(['token'=>$token])->find();
				if($user){
					$user['id'] = $user['uid'];
				}
			}
		}
		if(!empty($user)){
			$this->uid = $user['id'];
		}
		if($this->uid){
			$this->user = M('user')->where(['id'=>$this->uid])->find();
		}
		include_once CONF_PATH.'push.config.php';
// 		$where['token'] = I('token');
// 		$user = M('token')->where($where)->find();
// //		if (empty($user) && !in_array(ACTION_NAME, $this -> noCheck)) {
// //			_A(false, 'Token does not exist,Please login');
// //		}
// 		$this->uid = $user['uid'];
		
		$conf = C('options');
		$this->Easemob = new Easemob($conf); 
	}
	//个推  liuzm   begin 
	public function pushApp(){
		vendor('Gtpush.Igetui');
	    $igt = new \IGeTui(HOST,APPKEY,MASTERSECRET);
	    //$template = IGtTransmissionTemplateDemo();
	    $msg="good";
	    //$template =$this->IGtLinkTemplateDemo();
		$template = $this->IGtNotificationTemplateDemo($msg);
	    //个推信息体
	    //基于应用消息体
	    $message = new \IGtAppMessage();
	    $message->set_isOffline(true);
	    $message->set_offlineExpireTime(10 * 60 * 1000);//离线时间单位为毫秒，例，两个小时离线为3600*1000*2
	    $message->set_data($template);
	    $appIdList=array(APPID);
	    $message->set_appIdList($appIdList);
	   	$rep = $igt->pushMessageToApp($message,"任务组名");
	    echo ("<br><br>");
	}
	
	//单推接口案例
	function pushMessageToSingles(){
		//判断环信聊天是群还是单人
		$type	=	I('type');//1单聊，2群聊 
		$phone	=	I('phone');//type为1时，phone是手机号，为2时，phone是群号
		$msg	=	I('msg');//msg为1  您有一条新消息； msg 为2您有一条新的预约订单，请及时处理
		$from	=	I('from');//发送人
		switch ($msg) {
			case '1':
				$msg	=	"您有一条新消息";
				break;     
			case '2':
				$msg	=	"您有一条新的预约订单，请及时处理";
				break;
			default:
				$msg	=	"感谢您的参与,谢谢";
				break;
		}
		vendor('Gtpush.Igetui');
	    $igt = new \IGeTui(HOST,APPKEY,MASTERSECRET);
		switch ($type) { 
			case '1':
				$find	=	M('user')->where('phone="'.$phone.'"')->find();
				$cid	=	$find['clientid'];
				$equipment=	$find['eqsb'];
				if($cid!=""){//安卓
					// switch ($equipment) {
					// 	case 'android':
							$template = $this->IGtNotificationTemplateDemo($msg);
							
					// 		break;
					// 	case 'ios':
					// 		$template = $this->IGtTransmissionTemplateDemo($msg);
					// 		break;
					// 	default:
					// 		$template = $this->IGtNotificationTemplateDemo($msg);
					// 		break;
					// }
					
					$message = new \IGtSingleMessage();
					
				    $message->set_isOffline(true);//是否离线
				    $message->set_offlineExpireTime(3600*12*1000);//离线时间
				    $message->set_data($template);//设置推送消息类型
				    //接收方
				    $target = new \IGtTarget();
				    $target->set_appId(APPID);
					$target->set_clientId($cid);
					
					try {
				        $rep = $igt->pushMessageToSingle($message, $target);
        				$this->ajaxReturn(['s'=>true, 'm'=>'', 'rep'=>$rep]);
				    }catch(\RequestException $e){
				        $requstId =$e->getRequestId();
				        $rep = $igt->pushMessageToSingle($message, $target,$requstId);
        				$this->ajaxReturn(['s'=>true, 'm'=>'', 'rep'=>$rep]);
				    }
				}
				break;
			case '2':
				$result = $this->Easemob->getGroupUsers($phone);
				$data	=	$result['data'];
				if($from!=$data[0]['owner']){//判断信息是不是群主发的
					$finds	=	M('user')->where('phone="'.$data[0]['owner'].'"')->find();
					$cid	=	$finds['clientid'];
					$equipment=	$finds['eqsb'];
					if($cid!=''){
						// switch ($equipment) {
						// 	case 'android':
								$template = $this->IGtNotificationTemplateDemo($msg);
						// 		break;
						// 	case 'ios':
						// 		$template = $this->IGtTransmissionTemplateDemo($msg);
						// 		break;
						// 	default:
						// 		break;
						// }
					    //个推信息体
					    $message = new \IGtSingleMessage();
					    $message->set_isOffline(true);//是否离线
					    $message->set_offlineExpireTime(3600*12*1000);//离线时间
					    $message->set_data($template);//设置推送消息类型
					    //接收方
					    $target = new \IGtTarget();
					    $target->set_appId(APPID);
						$target->set_clientId($cid);
						try {
					        $rep = $igt->pushMessageToSingle($message, $target);
            				$this->ajaxReturn(['s'=>true, 'm'=>'', 'rep'=>$rep]);
					    }catch(\RequestException $e){
					        $requstId =$e->getRequestId();
					        $rep = $igt->pushMessageToSingle($message, $target,$requstId);
            				$this->ajaxReturn(['s'=>true, 'm'=>'', 'rep'=>$rep]);
					    }
					}
				}
				foreach ($data as  $value) {
					if($from!=$value['member']){
						$find	=	M('user')->where('phone="'.$value['member'].'"')->find();
						$cid	=	$find['clientid'];
						$equipment=	$find['eqsb'];
						if($cid!=''){
							// switch ($equipment) {
							// 	case 'android':
									$template = $this->IGtNotificationTemplateDemo($msg);
									break;
							// 	case 'ios':
							// 		$template = $this->IGtTransmissionTemplateDemo($msg);
							// 		break;
							// 	default:
							// 		break;
							// }
							$message = new \IGtSingleMessage();
						    $message->set_isOffline(true);//是否离线
						    $message->set_offlineExpireTime(3600*12*1000);//离线时间
						    $message->set_data($template);//设置推送消息类型
						    //接收方
						    $target = new \IGtTarget();
						    $target->set_appId(APPID);
							$target->set_clientId($cid);
							try {
						        $rep = $igt->pushMessageToSingle($message, $target);
						        echo ("<br><br>");
						    }catch(\RequestException $e){
						        $requstId =$e->getRequestId();
						        $rep = $igt->pushMessageToSingle($message, $target,$requstId);
						        echo ("<br><br>");
						    }
						}
					}
				}
				break;
			default:
				echo "please write type";exit;
				break;
		}
	}
	//end
	function IGtNotificationTemplateDemo($msg){
		vendor('Gtpush.Igetui');
	    $template =  new \IGtNotificationTemplate();
	    $template->set_appId(APPID);//应用appid
	    $template->set_appkey(APPKEY);//应用appkey
	    $template->set_transmissionType(1);//透传消息类型
	    $template->set_transmissionContent("测试离线");//透传内容
	    $template->set_title("娱管家");//通知栏标题
	    $template->set_text($msg);//通知栏内容
	    //$template->set_text('test');//通知栏内容
	    $template->set_logo("http://www.yuzhuli.com/login.png");//通知栏logo
	    $template->set_isRing(true);//是否响铃
	    $template->set_isVibrate(true);//是否震动
	    $template->set_isClearable(true);//通知栏是否可清除
	    
	    return $template;
	}
	function IGtTransmissionTemplateDemo($msg){
		switch ($msg) {
			case '1':
				$title	=	"您有一条新消息";
				break;     
			case '2':
				$title	=	"您有一条新的预约订单，请及时处理";
				break;
			default:
				$title	=	"您有一条新消息";
				break;
		}
        $template =  new \IGtTransmissionTemplate();
        $template->set_appId(APPID);//应用appid
        $template->set_appkey(APPKEY);//应用appkey
        $template->set_transmissionType(1);//透传消息类型
        $template->set_transmissionContent("测试离线ddd");//透传内容
//       APN高级推送
        $apn = new \IGtAPNPayload();
        $alertmsg=new \DictionaryAlertMsg();
        $alertmsg->body="请您及时查看";			//通知文本消息字符串
        $alertmsg->actionLocKey="ActionLockey";	//(用于多语言支持）指定执行按钮所使用的Localizable.strings
        $alertmsg->locKey="LocKey";				//(用于多语言支持）指定Localizable.strings文件中相应的key
        $alertmsg->locArgs=array("locargs");
        $alertmsg->launchImage="launchimage";	//指定启动界面图片名
//        iOS8.2 支持
        $alertmsg->title=$title;			//通知标题
        $alertmsg->titleLocKey="TitleLocKey";	//(用于多语言支持）对于标题指定执行按钮所使用的Localizable.strings,仅支持iOS8.2以上版本
        $alertmsg->titleLocArgs=array("TitleLocArg");//对于标题, 如果loc-key中使用的占位符，则在loc-args中指定各参数,仅支持iOS8.2以上版本
        $apn->alertMsg=$alertmsg;
        $apn->badge=0;			//应用icon上显示的数字
        $apn->sound="";			//通知铃声文件名
        $apn->add_customMsg("payload","");//增加自定义的数据
        $apn->category="ACTIONABLE";	//在客户端通知栏触发特定的action和button显示
        $template->set_apnInfo($apn);
        return $template;
	}
	
	
	
	//环信
	public function around(){

		$uid	= $this->uid;
		$user	= $this->user; 
		$dat 	= I(); 
		$id  	= I('id');
		switch($id){
			case 1 ://获取用户所在的群组
				$user = $user['phone'];
				$result = $this->Easemob->getCustomerGroup($user);
				foreach ($result['data'] as $key => $value) {
					$group	=	M('group')->where('group_id="'.$value['groupid'].'"')->find();
					$result['data'][$key]['img']	=	$group['img'];
				}
				$this->ajaxReturn(array('s'=>true,'d'=>$result['data']));
				break;
			case 2 ://获取一个群详情
				$group_num	=	I('group_num');
				$group_ids=array($group_num);
				$result = $this->Easemob->getGroupDetail($group_ids);
				$data=$result['data'];
				foreach ($data as $key => $value) {
					foreach ($value['affiliations'] as $k => $v) {
						foreach ($v as $i => $d) {
							$list=M('user')->where('phone="'.$d.'"')->find();
							$value['affiliations'][$k]['img']=$list['img'];
						}
						
					}
				}
				$data=$value;
				$group	=	M('group')->where('group_id="'.$group_num.'"')->find();
				if($uid!=$group['uid']){
					$data['g_status']=0;
				}else{
					$data['g_status']=1;
				}
				$data['group_img']=$group['img'];
				$this->ajaxReturn(array('s'=>true,'d'=>$data));
				break;
			case 3://修改群组信息
				$group_id	=	I('group_num');
				$img =$this->uploadimg('img');
				$options['groupname']=I('groupname');
				$options['description']=I('description');
				$options['maxusers']=I('maxusers')>0?I('maxusers'):300;
				$result = $this->Easemob->modifyGroupInfo($group_id,$options);
				$data	=	array(
						'img'	=>	$img,
						'group_name'=>I('groupname'),
					);
				$where=array('group_id'=>$group_id,'uid'=>$uid);
				$res_save	=	M('group')->where($where)->save($data);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 4://删除群组
				$group_id=I('groupid');
				$name=I('name');
				$list=M('group')->where('group_id="'.$group_id.'"')->find();
				if($name!=$list['owner']){
					$result = $this->Easemob->deleteGroupMember($group_id,$name);
					$this->ajaxReturn(array('s'=>true,'d'=>'退群成功'));	
				}else{
					$result = $this->Easemob->deleteGroup($group_id);
					M('group')->where('group_id="'.$group_id.'"')->delete();
					$this->ajaxReturn(array('s'=>true,'m'=>'success'));
				}
				break;
			case 5://获取群组中的成员
				$group_id="122633509780062768";
				$result = $this->Easemob->getGroupUsers($group_id);
				break;
			case 6://历史记录以及头像
				$my_img	=	$user['img'];
				$fname	=	I('fname');
				$list	=	M('user')->where('phone="'.$fname.'"')->find();
				$result	=	array('my_img'=>$my_img,'f_img'=>$list['img']);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 7:
				$name	=	I('name');
				$where['group_name'] = array('eq',$name);
				$list	=	M('group')->where($where)->select();
				foreach ($list as $key => $value) {
					$data[$key]['name']=$value['group_name'];
					$data[$key]['img'] =$value['img'];
					$data[$key]['group_id'] =$value['group_id'];
				}
				$this->ajaxReturn(array('s'=>true,'d'=>$data));
				break;
			case 10://获取token
				$result = $this->Easemob->getToken();
				break;
			case 11://创建单个用户  
				$result = $this->Easemob->createUser('13938720154','12345'); 
				
				break;
			case 12://创建批量用户
				$result = $this->Easemob->createUsers(array(
					array(
						"username"=>"zhangsan",
						"password"=>"123456"
					),
					array(
						"username"=>"lisi",
						"password"=>"123456"
					)
				));
				break;
			case 13://重置用户密码
				$result = $this->Easemob->resetPassword(array_shift($parm),array_shift($dat));
				break;
			case 14://获取单个用户
				$name	=	I('name'); 
				$result = $this->Easemob->getUser($name);
				$data=$result['entities'];
				foreach ($data as $key => $value) {
					$user=M('user')->where('phone="'.$name.'"')->find();
					$data[$key]['ourimg']=$user['img'];
					$data[$key]['ournickname']=$user['nickname'];
				}
				$this->ajaxReturn(array('s'=>'true','d'=>$data));
				break;
			case 15://获取批量用户---不分页(默认返回10个)
				$result = $this->Easemob->getUsers();
				break;
			case 16://获取批量用户----分页
				$cursor=$this->Easemob->readCursor("userfile.txt");
				$result = $this->Easemob->getUsersForPage(10,$cursor);
				break;
			case 17://删除单个用户
				$result = $this->Easemob->deleteUser("zhangsan");
				break;
			case 18://删除批量用户
				$result = $this->Easemob->deleteUsers(2);
				break;
			case 19://修改昵称
				$result = $this->Easemob->editNickname("zhangsan","小B");
				break;
				
			case 20://添加好友------400
				$my_name	=	I('name');
				$fname		=	I('fname');
				$result = $this->Easemob->addFriend($my_name,$fname);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 21://删除好友
				$fname		=	I('fname');
				$result = $this->Easemob->deleteFriend($user['phone'], $fname);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 22://查看好友
				$result = $this->Easemob->showFriends($user['phone']);
				$userinfo=array();
				foreach ($result['data'] as $key => $value) {
					$userinfo[$key]	=	M('user')->where('phone="'.$value.'"')->find();
				}
				$this->ajaxReturn(array('s'=>true,'d'=>$userinfo));
				break;
			case 23://查看黑名单
				$result = $this->Easemob->getBlacklist("zhangsan");
				break;
			case 24://往黑名单中加人
				$usernames=array(
					"usernames"=>array("wangwu","lisi")
				);
				$result = $this->Easemob->addUserForBlacklist("zhangsan",$usernames);
				break;
			case 25://从黑名单中减人
				$result = $this->Easemob->deleteUserFromBlacklist("zhangsan","lisi");
				break;
			case 26://查看用户是否在线
				$result = $this->Easemob->isOnline("liu123");
				break;
			case 27://查看用户离线消息数
				$result = $this->Easemob->getOfflineMessages("15553923158");
				break;
			case 28://查看某条消息的离线状态
				$result = $this->Easemob->getOfflineMessageStatus("zhangsan","77225969013752296_pd7J8-20-c3104");
				break;
			case 29://禁用用户账号----
				$result = $this->Easemob->deactiveUser("zhangsan");
				break;
			case 30://解禁用户账号-----
				$result = $this->Easemob->activeUser("zhangsan");
				break;
			case 31://强制用户下线
				$result = $this->Easemob->disconnectUser("zhangsan");
				break;
			case 32://上传图片或文件
				$result = $this->Easemob->uploadFile("./resource/up/pujing.jpg");
				//$result = $this->Easemob->uploadFile("./resource/up/mangai.mp3"));
				//$result = $this->Easemob->uploadFile("./resource/up/sunny.mp4"));
				break;
			case 33://下载图片或文件
				$result = $this->Easemob->downloadFile('01adb440-7be0-11e5-8b3f-e7e11cda33bb','Aa20SnvgEeWul_Mq8KN-Ck-613IMXvJN8i6U9kBKzYo13RL5');
				break;
			case 34://下载图片缩略图
				$result = $this->Easemob->downloadThumbnail('01adb440-7be0-11e5-8b3f-e7e11cda33bb','Aa20SnvgEeWul_Mq8KN-Ck-613IMXvJN8i6U9kBKzYo13RL5');
				break;
			case 35://发送文本消息  用户  type 1   群组  type 2
				$from	=	I('name');
				$type	=	I('type');
				if($type == 1){
					$toname 	= I('fname');
					$target_type= "users";
					$target 	= array($toname);
				}else{
					$toname 	= I('fname');
					$target_type= "chatgroups";
					$target 	= array($toname);//群id
				}
				$content 	= I('content');
				$ext['a'] 	= "a";
				$ext['b']	= "b";
				$result 	= $this->Easemob->sendText($from, $target_type, $target, $content, $ext);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 36://发送透传消息
				$from 		= 'admin';
				$target_type= "users";
				//$target_type="chatgroups";
				$target 	= array("zhangsan","lisi","wangwu");
				//$target=array("122633509780062768");
				$action 	= "Hello HuanXin!";
				$ext['a']	= "a";
				$ext['b']	= "b";
				$result = $this->Easemob->sendCmd($from, $target_type, $target, $action, $ext);
				break;
			case 37://发送图片消息
				$imgdata=I('imgdata');
				$fileimg=$this->uploadimg($imgdata);
				$getinfo=$this->Easemob->uploadFile($fileimg);
				
				exit;
				
				$filePath="./resource/up/pujing.jpg";
				$from='admin';
				$target_type="users";
				$target=array("zhangsan","lisi");
				$filename="pujing.jpg";
				$ext['a']="a";
				$ext['b']="b";
				$result = $this->Easemob->sendImage($filePath,$from,$target_type,$target,$filename,$ext);
				break;
			case 38://发送语音消息
				$filePath="./resource/up/mangai.mp3";
				$from='admin';
				$target_type="users"; //users 给用户发消息。chatgroups: 给群发消息，chatrooms: 给聊天室发消息
				$target=array("zhangsan","lisi");
				$filename="mangai.mp3";
				$length=10;
				$ext['a']="a";
				$ext['b']="b";
				$result = $this->Easemob->sendAudio($filePath,$from="admin",$target_type,$target,$filename,$length,$ext);
				break;
			case 39://发送视频消息
				$filePath="./resource/up/sunny.mp4";
				$from='admin';
				$target_type="users";
				$target=array("zhangsan","lisi");
				$filename="sunny.mp4";
				$length=10;//时长
				$thumb='https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/c06588c0-7df4-11e5-932c-9f90699e6d72';
				$thumb_secret='wGWIyn30EeW9AD1fA7wz23zI8-dl3PJI0yKyI3Iqk08NBqCJ';
				$ext['a']="a";
				$ext['b']="b";
				$result = $this->Easemob->sendVedio($filePath,$from="admin",$target_type,$target,$filename,$length,$thumb,$thumb_secret,$ext);
				break;
			case 40://发文件消息
			
				break;
			case 41://获取app中的所有群组-----不分页（默认返回10个）
				$result = $this->Easemob->getGroups();
				break;
			case 42:////获取app中的所有群组--------分页
				$cursor=$this->Easemob->readCursor("groupfile.txt");
				$result = $this->Easemob->getGroupsForPage(2,$cursor);
				break;
			case 43://获取一个或多个群组的详情
				$group_ids=array("1445830526109","1445833238210");
				$result = $this->Easemob->getGroupDetail($group_ids);
				break;
			case 44://创建一个群组
				$uid	=	$this->uid;
				$img =$this->uploadimg('img');
				$options ['groupname'] = $dat['groupname'];
				$options ['desc'] = $dat['desc'];
				$options ['public'] = true;
				$options ['owner'] = $user['phone'];
				$options['members']=array();//array
				$result = $this->Easemob->createGroup($options);
				foreach ($result['data'] as $key => $value) {
					$group_id	=	$value;	
				}
				$data	=	array(
						'uid'	=>	$uid,
						'group_id'	=>	$group_id,
						'img'	=>	$img,
						'owner'=>$user['phone'],
						'group_name'=>$dat['groupname'],
					);
				$res_add	=	M('group')->add($data);
				if(false !== $res_add){
					$this->ajaxReturn(array('s'=>true,'d'=>$result));
				}
				break;
			
			case 48://群组单个加人------
				$group_id=I('group_id');
				$username=I('name');
				$result = $this->Easemob->addGroupMember($group_id,$username);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 49://群组批量加人
				$group_id=I('group_id');
				$usernames['usernames']=I('username');
				//$usernames['usernames']=array("wangwu","lisi");
				$result = $this->Easemob->addGroupMembers($group_id,$usernames);
				$this->ajaxReturn(array('s'=>true,'d'=>$result));
				break;
			case 50://群组单个减人
				//$group_id="122633509780062768";
				$group_id=I('groupid');//群id
				$username=I('name');//人名
				$result = $this->Easemob->deleteGroupMember($group_id,$username);
				
				$this->ajaxReturn(array('s'=>true,'d'=>$result));	
				break;
			case 51://群组批量减人-----
				$group_id="122633509780062768";
				//$usernames['usernames']=array("wangwu","lisi");
				$usernames='wangwu,lisi';
				$result = $this->Easemob->deleteGroupMembers($group_id,$usernames);	
				break;
			case 52://获取一个用户参与的所有群组
				$result = $this->Easemob->getGroupsForUser("zhangsan");
				break;
			case 53://群组转让
				$group_id="122633509780062768";
				$options['newowner']="lisi";
				$result = $this->Easemob->changeGroupOwner($group_id,$options);
				break;
			case 54://查询一个群组黑名单用户名列表
				$group_id="122633509780062768";
				$result = $this->Easemob->getGroupBlackList($group_id);
				break;
			case 55://群组黑名单单个加人-----
				$group_id="122633509780062768";
				$username="lisi";
				$result = $this->Easemob->addGroupBlackMember($group_id,$username);		
				break;
			case 56://群组黑名单批量加人
				$group_id="122633509780062768";
				$usernames['usernames']=array("lisi","wangwu");
				$result = $this->Easemob->addGroupBlackMembers($group_id,$usernames);		
				break;
			case 57://群组黑名单单个减人
				$group_id="122633509780062768";
				$username="lisi";
				$result = $this->Easemob->deleteGroupBlackMember($group_id,$username);		
				break;
			case 58://群组黑名单批量减人
				$group_id="122633509780062768";
				$usernames['usernames']=array("wangwu","lisi");
				$result = $this->Easemob->deleteGroupBlackMembers($group_id,$usernames);		
				break;
			case 59://创建聊天室
				$options ['name'] = "chatroom001";
				$options ['description'] = "this is a love chatroom";
				$options ['maxusers'] = 300;
				$options ['owner'] = "zhangsan";
				$options['members']=Array("man","lisi");
				$result = $this->Easemob->createChatRoom($options);	
				break;
			case 69://导出聊天记录-------不分页
				$ql="select+*+where+timestamp>1435500000000&limit=1000";
				$result = $this->Easemob->getChatRecord($ql);
				
				break;
			case 70://导出聊天记录-------分页
				$ql="select+*+where+timestamp>1435536480000";
				$cursor=$this->Easemob->readCursor("./chatfile.txt");
				//$result = $this->Easemob->$cursor);
				$result = $this->Easemob->getChatRecordForPage($ql,10,$cursor);
				break;
			case 71:// 发送文本消息  用户  type 1   群组  type 2
				$from		=	I('from');//发送人username
				$chat_type	=	I('chat_type');//chat: 单聊；groupchat: 群聊
				$msg		=	I('msg');
				$to 		=	I('to');
				
				$data	=	array(
					'from'		=> $from,
					'to'		=> $to,
					'msg_id'	=> 0,//消息ID
					'chat_type'	=> $chat_type,//用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
					'timestamp'	=> time()*1000,
					'msg'		=> $msg,
					'type'		=> 'txt',
				);
				$result = M('msg')->add($data);
				$this->ajaxReturn(['s' => $result ? true : false]);	
				break;
			// case 72:// 发送图片
			// 	$from		= I('from');//发送人username
			// 	$chat_type	= I('chat_type');//chat: 单聊；groupchat: 群聊
			// 	$to 		= I('to');
			// 	$url 		= $this->uploadimg('data');
			// 	$data	= array(
			// 		'from'		=> $from,// 发送者 手机号
			// 		'to'		=> $to,// 接收者 手机号或群id
			// 		'msg_id'	=> 0,//消息ID
			// 		'chat_type'	=> $chat_type,// 用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
			// 		'timestamp'	=> time()*1000,
			// 		'url'		=> $url,
			// 		'type'		=> 'img',
			// 	);
			// 	$result = M('msg')->add($data);
			// 	$this->ajaxReturn(['s' => $result ? true : false]);	
			// 	break;
			// case 73:// 
				
			// 	break;
		}
	}
	public function uploadimg($key) {
		$imgData =I($key);
		if(is_array($imgData)){
			$resutl = array();
			foreach($imgData as $img){
				$resutl[] = $this->saveOneImage($img);
			} 
			$resutl = implode(',', $resutl);
		}else{
			$resutl = $this->saveOneImage($imgData);
		}
		return $resutl; 
	}
	public function saveOneImage($dataString){
		$img = explode(',', $dataString);
		$npath = ''.C('UPLOAD_PATH').'/userimg/';
		$nfilename = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$exe =  str_replace('data:image/', '', $img[0]);  //data:image/png;base64
		$exe =  str_replace(';base64', '', $exe); 
		$newName = $npath . $nfilename . '.'.$exe;
		file_put_contents($newName, base64_decode($img[1]));
		if($exe == 'png'){
			$image = imagecreatefrompng($newName);
		}else{
			$image = imagecreatefromjpeg($newName);
		}
		$exif = exif_read_data($newName);
		if(!empty($exif['Orientation'])) {
		 switch($exif['Orientation']) {
		  case 8:
		   $image = imagerotate($image,90,0);
		   break;
		  case 3:
		   $image = imagerotate($image,180,0);
		   break;
		  case 6:
		   $image = imagerotate($image,-90,0);
		   break;
		 }
		}
		if($exe == 'png'){
			imagepng ($image,$newName);
		}else{
			imagejpeg ($image,$newName);
		}
		return C("SiteUrl").$newName;
	}
	
	public function uploadAudio($key) {
		$imgData =$key;
		if(is_array($imgData)){
			$resutl = array();
			foreach($imgData as $img){
				$resutl[] = $this->saveAudio($img);
			} 
			$resutl = implode(',', $resutl);
		}else{
			$resutl = $this->saveAudio($imgData);
		}
		return $resutl; 
	}
	public function saveAudio($dataString){
		$img = explode(',', $dataString);
		$npath = ''.C('UPLOAD_PATH').'/userimg/';
		$nfilename = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$newName = $npath . $nfilename . '.amr'; 
		file_put_contents($newName, base64_decode($img[1]));
		return C("SiteUrl").$newName;
	}
	
	//存储消息
	public function save_msg(){
  		$type		=	I('type');
		$category	=	I('category');
		$from		=	I('from');
		$content	=	I('content');
		$to			=	I('to');
		$ctime		=	time();
		$data		=	array(
							'type'=>$type,
							'category'=>$category,
							'content'=>$content,
							'from'=>$from,
							'to'=>$to,
							'ctime'=>$ctime	,
						);
		$res_add	=	M('msg')->add($data);
		if(false !== $res_add){
			$this->ajaxReturn(array('s'=>true));
		}else{
			$this->ajaxReturn(array('s'=>false));
		}
		
	}
	
	//聊天记录
	public function  history_msg(){
		$type	=	I('type');//1单聊  2 群聊    //用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
		$name	=	I('name');
		$fname	=	I('fname');
		switch ($type) {
			case '1':
				$read_status=M('msg')->where(array('from'=>$fname,'to'=>$name))->data(array('read_status'=>1))->save();//修改已读状态
				$where1	=	array('from'=>$name,'to'=>$fname);
				$list_my=	M('msg')->where($where1)->order('timestamp desc')->limit('10')->select();
				foreach ($list_my as $key => $value) {
					$list_my[$key]['time']=date('Y-m-d H:i',$value['timestamp']/1000);
					$img	=	M('user')->where('phone="'.$value['from'].'"')->find();
					$list_my[$key]['img']=$img['img'];
					$list_my[$key]['nickname']=$img['nickname'];
					$list_my[$key]['content']=html_entity_decode($value['msg']);
				}
				if($fname != $name){
					$where2	=	array('from'=>$fname,'to'=>$name);
					$list_other=M('msg')->where($where2)->order('timestamp desc')->limit('10')->select();
					foreach ($list_other as $key => $value) {
						$list_other[$key]['time']=date('Y-m-d H:i',$value['timestamp']/1000);
						$img	=	M('user')->where('phone="'.$value['from'].'"')->find();
						$list_other[$key]['img']=$img['img'];
						$list_other[$key]['nickname']=$img['nickname'];
						$list_other[$key]['content']=html_entity_decode($value['msg']);
					}
					$result = array_merge($list_my,$list_other);
				}else{
					$result = $list_my;
				}
			
				$result = $this->array_sort($result,'timestamp','asc');
				
				$returndata = array();
				foreach($result as $re){
					$returndata[] = $re;
				}
				
				$returndata = array_slice($returndata, -10);
				$this->ajaxReturn(array('s'=>true,'d'=>$returndata));
				break;
			case  '2':
				$group_ids=array($fname);
				//群的话   往状态表里面加一条，有就更新begin
				$msg_status=array('from'=>$name,'to'=>$fname);
				$msg_sta=array('to'=>$fname);
				$find_msg=M('msg_status')->where($msg_status)->find();
				$list_find_msg=M('msg')->where($msg_sta)->order('timestamp desc')->find();
				if(empty($list_find_msg)){
					$list_find_msg['timestamp']='1435500000000';
				}
				if(!empty($find_msg)){
					M('msg_status')->where($msg_status)->data(array('timestamp'=>$list_find_msg['timestamp']))->save();
				}else{
					M('msg_status')->data(array('timestamp'=>$list_find_msg['timestamp'],'from'=>$name,'to'=>$fname))->add();
				}
				//群的话   往状态表里面加一条，有就更新end
				$results = $this->Easemob->getGroupDetail($group_ids);
				$data=$results['data'];
				foreach ($data as $key => $value) {
					$group_name=$value['name'];
				}
				$group	=	M('group')->where('group_id="'.$group_num.'"')->find();
				$data['group_img']=$group['img'];
				$where1	=	array('from'=>$name,'to'=>$fname);
				$list_my=	M('msg')->where($where1)->order('timestamp desc')->limit('10')->select();
				foreach ($list_my as $key => $value) {
					$list_my[$key]['time']=date('Y-m-d H:i',$value['timestamp']/1000);
					$img	=	M('user')->where('phone="'.$value['from'].'"')->find();
					$list_my[$key]['img']=$img['img'];
					$list_my[$key]['nickname']=$img['nickname'];
					$list_my[$key]['content']=html_entity_decode($value['msg']);
				}
				$where2	=	array('to'=>$fname);
				$list_other=M('msg')->where($where2)->where('`from`!="'.$name.'"')->order('timestamp desc')->limit('10')->select();
				foreach ($list_other as $key => $value) {
					$list_other[$key]['time']=date('Y-m-d H:i',$value['timestamp']/1000);
					$img	=	M('user')->where('phone="'.$value['from'].'"')->find();
					$list_other[$key]['img']=$img['img'];
					$list_other[$key]['nickname']=$img['nickname'];
					$list_other[$key]['content']=html_entity_decode($value['msg']);
				}
				$result = array_merge($list_my,$list_other);
				$result = $this->array_sort($result,'timestamp','asc');
				$returndata = array();
				foreach($result as $re){
					$returndata[] = $re;
				} 
				$returndata = array_slice($returndata,-10);
				$this->ajaxReturn(array('s'=>true,'d'=>$returndata));
				break;
			default:
				break;
		}
		
	}
	function array_sort($arr,$keys,$type='asc'){ 
		 $keysvalue = $new_array = array();
		 foreach ($arr as $k=>$v){
		  	$keysvalue[$k] = $v[$keys];
		 }
		 if($type == 'asc'){
		  	asort($keysvalue);
		 }else{
		  	arsort($keysvalue);
		 }
		 reset($keysvalue);
		 foreach ($keysvalue as $k=>$v){
		  	$new_array[$k] = $arr[$k];
		 }
		 return $new_array; 
	}
	public function head_img(){
			$uid	=	$this->uid;
			$user	=	M('user')->find($uid);
			$name	=	I('name');
			$fname	=	I('fname');
			$where	=	array('phone'=>$fname);
			$list 	=	M('user')->where($where)->find();
			$data['my']=$user['img'];
			$data['other']=$list['img'];
			$data['nickname']=$list['nickname'];
			$this->ajaxReturn(array('s'=>true,'d'=>$data));
	}
	//获取整组图片
	public function head_imgs(){
			$phone	=	I('phone');//数组
			$imgData=array();
			foreach ($phone as $key => $value) {
				$where	=	array('phone'=>$value);
				$list 	=	M('user')->where($where)->find();
				$imgData[$key]['img'] =	$list['img'];
				$imgData[$key]['phone'] =	$list['phone'];
				$imgData[$key]['nickname'] =	$list['nickname'];
			}
			$this->ajaxReturn(array('s'=>true,'d'=>$imgData));
	}
	/**
	 * @author 	liuzm
	 * @date   	2016年12月15日13:34:43
	 * @name	msg_list
	 * @desc	消息列表
	 * */
	public function msg_list(){
		$name		=	I('name');
		$list_from	=	M('msg')->field('`to` as A')->where('`from`="'.$name.'" and `status`!=1')->group('`to`')->order('timestamp desc')->select();//自己发给别人
		$list_to	=	M('msg')->field('`from` as A')->where('`to`="'.$name.'" and `status`!=1')->group('`from`')->order('timestamp desc')->select();//自己发给别人
		$tmptouser	=	array_merge($list_from,$list_to);
		$touser = array();
		foreach($tmptouser as $d){ 
			if(!in_array($d['a'], $touser)) $touser[] = $d['a'];
		}
		$msgList = array();
		foreach ($touser as $u) {
			$mes = M('msg')->where('(`to`="'.$name.'" and `from`="'.$u.'" and `status`="0") or (`to`="'.$u.'" and `from`="'.$name.'"  and `status`="0" )  ')->order('timestamp desc')->limit(1)->find();
			//echo M()->_sql();exit;
			$mes['ctimeStr'] = date('Y-m-d H:i:s',$mes['timestamp']/1000);
			$mes['msg'] = html_entity_decode($mes['msg']);
			//未读消息
			if(strlen($u)<12){
				$where_status=array('from'=>$u,'to'=>$name,'read_status'=>0);
				$msg_wei	=	M('msg')->where($where_status)->where('status!=1')->select();
				$mes['unread'] =count($msg_wei);
			}
			$msgList[] = $mes;			
		}
		$time = array();
		foreach ($msgList as $key=>$value){
		    $time[$key] = $value['timestamp']; 
		}
		array_multisort($time,SORT_NUMERIC,SORT_DESC,$msgList); 
		foreach ($msgList as $k => $v) {
			$num_from	=	strlen($v['from']);
			$num_to	=	strlen($v['to']);
			if($num_from>12){
				$group_ids=array($v['from']);
				$result = $this->Easemob->getGroupDetail($group_ids);
				$datas=$result['data'];
				foreach ($datas as $key => $value) {
					foreach ($value['affiliations'] as $ks => $vs) {
						foreach ($vs as $i => $d) {
							$list=M('user')->where('phone="'.$d.'"')->find();
							$value['affiliations'][$ks]['img']=$list['img'];
						}
					}
				}
				$datas=$value;
				$group	=	M('group')->where('group_id="'.$v['to'].'"')->find();
				$msgList[$k]['from_group_nickname']=$datas['name'];
				$msgList[$k]['from_group_img']=$group['img'];
			}else{
				$da	=	M('user')->where('`phone`="'.$v['from'].'"')->find();
				$msgList[$k]['from_nickname']=$da['nickname'];
				$msgList[$k]['from_img']=$da['img'];
			}
			if($num_to>12){
				$group_ids=array($v['to']);
				$result = $this->Easemob->getGroupDetail($group_ids);
				//获取群的未读消息begin
				$where_status=array('to'=>$v['to'],'from'=>$name);
				$msg_status =  M('msg_status')->where($where_status)->find();
				if(!empty($msg_status)){
					$condition	=  array('to'=>$v['to']);
					$condition['timestamp']=array('gt',$msg_status['timestamp']);
				}else{
					$condition	=  array('to'=>$v['to']);
				}
				$Unread_num =  M('msg')->where($condition)->select();
				$msg_num = 0 ;
				foreach($Unread_num as $n => $m  ){
					if($name != $m['from']){
						$msg_num=$msg_num+1;
					}
				}
				$msgList[$k]['unread']=$msg_num;
				//获取群的未读消息end
				$datas=$result['data'];
				foreach ($datas as $key => $value) {
					foreach ($value['affiliations'] as $ks => $vs) {
						foreach ($vs as $i => $d) {
							$list=M('user')->where('phone="'.$d.'"')->find();
							$value['affiliations'][$ks]['img']=$list['img'];
						}
					}
				}
				$datas=$value;
				$group	=	M('group')->where('group_id="'.$v['to'].'"')->find();
				$msgList[$k]['to_nickname']=$datas['name'];//群名
				$msgList[$k]['to_img']=$group['img'];//群的头像
			}else{
				$da	=	M('user')->where('`phone`="'.$v['to'].'"')->find();
				$msgList[$k]['to_nickname']=$da['nickname'];//用户昵称
				$msgList[$k]['to_img']=$da['img'];//用户头像
			}
		}
		foreach ($msgList as $k => $v) {
			$num_len=strlen($v['to']);
			if($num_len >11){
				$content_list	=	M('msg')->where('`to`="'.$v['to'].'"')->where('status!=1')->order('timestamp desc')->find();
				$msgList[$k]['msg']=html_entity_decode($content_list['msg']);
				$msgList[$k]['type']=$content_list['type'];
				$msgList[$k]['secret']=$content_list['secret'];
			}
		}
		$this->ajaxReturn(array('s'=>true,'d'=>$msgList));
	}

	
	
	//上传图片到环信
	public function uppic(){
		//$data	=	$_POST['data'];
		$url	= $this->uploadimg('data');
		
		$result = $this->Easemob->uploadFile($url);		
		
	}
	//下载
	public function downFile(){
		$result = $this->Easemob->downloadFile('d32e7bb0-d195-11e6-b620-23c22255a62d','0y57utGVEeaXRq2fcU8hD2W7cNt-wmZmg00nL_O3-v9EqHpP');
		
	}
	
	//sendImage
	public function sendImage(){
	    $filePath	 = $this->uploadimg('data');
		$from 		 = I('from');//发送人username
		$target_type = I('target_type');
		$people		 = I('people');
		$target 	 = array($people);
		$filename    = "test.jpg";
		$ext['a']    = "a";
		$ext['b']    = "b";
		$img_result  = $this->Easemob->sendImage($filePath,$from,$target_type,$target,$filename,$ext);

		$chat_type	= I('chat_type');//chat: 单聊；groupchat: 群聊
		$to 		= I('to');
		$data	= array(
			'from'		=> $from,// 发送者 手机号
			'to'		=> $to,// 接收者 手机号或群id
			'msg_id'	=> 0,//消息ID
			'chat_type'	=> $chat_type,// 用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
			'timestamp'	=> time()*1000,
			'url'		=> $filePath,
			'type'		=> 'img',
		);
		$result = M('msg')->add($data);
		$this->ajaxReturn(['s' => $result ? true : false, 'd'=>$img_result]);	
				
		// $this->ajaxReturn(array('s'=>true,'d'=>$img_url));
	}
	
	
	
	//sendAudio
	public function sendAudio(){
		// $getID3 = new \Common\Utils\getID3();
// die;
	 	$data 			= $_POST['data'];
	 	$type           = I('type', 'file');
	 	if($type == 'url'){
	 		$filePath = $data;
	 	}else{
			$filePath = $this->uploadAudio($data);
	 	}
		$from 			= I('from');
		$target_type    = I('target_type'); //users 给用户发消息。chatgroups: 给群发消息，chatrooms: 给聊天室发消息
		$to 			= I('to');
		$target 		= array($to);
		$filename 		= "one.mp3";
		$length 		= 10;
		$ext['a'] 		= "a";
		$ext['b']       = "b";
		$audio_result 	= $this->Easemob->sendAudio($filePath,$from,$target_type,$target,$filename,$length,$ext);

		$chat_type	= I('chat_type');//chat: 单聊；groupchat: 群聊
		$data	= array(
			'from'		=> $from,// 发送者 手机号
			'to'		=> $to,// 接收者 手机号或群id
			'msg_id'	=> 0,//消息ID
			'chat_type'	=> $chat_type,// 用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
			'timestamp'	=> time()*1000,
			'url'		=> $filePath,
			// 'length'	=> getAudioDuration($filePath),
			'type'		=> 'audio',
		);
		$result = M('msg')->add($data);
		$this->ajaxReturn(array('s'=>true,'d'=>$filePath));
	}
	
	
	public function getMsgList(){
		// $find	=	M('msg')->order('id desc')->find();
		// if(!empty($find)){
		// 	$timestamp	=	$find['timestamp'];
		// }else{
		// 	$timestamp	=	'1435500000000';
		// }
		// $ql="select+*+where+timestamp>".$timestamp."&limit=1000";
		// $result = $this->Easemob->getChatRecord($ql);
		
		// foreach ($result['entities'] as $value) {
		// 	$from	=	$value['from'];	//发送人username
		// 	$to		=	$value['to'];	//接收人的username或者接收group的ID
		// 	$msg_id	=	$value['msg_id'];//消息ID
		// 	$chat_type=	$value['chat_type'];//用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
		// 	$timestamp=	$value['timestamp'];//消息发送时间  
		// 	foreach ($value['payload']['bodies'] as $v) {
		// 		$msg	=	$v['msg'];//消息内容
		// 		$type	=	$v['type'];//消息类型。txt: 文本消息；img: 图片；loc: 位置；audio: 语音
		// 		$length	=	$v['length']; //语音时长，单位为秒，这个属性只有语音消息有
		// 		$url	=	$v['url'];//图片语音等文件的网络URL，图片和语音消息有这个属性
		// 		$filename=	$v['filename'];//图片语音等文件的网络URL，图片和语音消息有这个属性
		// 		$secret	=	$v['secret'];//获取文件的secret，图片和语音消息有这个属性
		// 	}
		// 	$data	=	array(
		// 		'from'	=>	$from,
		// 		'to'	=>	$to,
		// 		'msg_id'=>	$msg_id,
		// 		'chat_type'	=>$chat_type,
		// 		'timestamp'	=>	$timestamp,
		// 		'msg'	=>	$msg,
		// 		'type'	=>	$type,
		// 		'length'=>	$length,
		// 		'url'	=>	$url,
		// 		'filename'=>$filename,
		// 		'secret' =>	$secret,
		// 	);
		// 	try{
		// 		$result = M('msg')->add($data);
		// 	}catch(Exception $e){
		// 		$this -> ajaxReturn(array('s' => false));	
		// 	}
		// }
		// $this -> ajaxReturn(array('s' => true));
	}
	
	/*
	 * liuzm
	 * 2017年1月17日20:40:48
	 * 删除好友   把消息列表状态  msg的status 改为1
	*/
	public function delFriend(){
		$name	=	I('name');
		$toname	=	I('toname');//如果退群的话   此字段为退群的群号
		$data=array('status'=>1);
		$where=array('from'=>$name,'to'=>$toname);
		try{
				$list=M('msg')->where($where)->save($data);
			}
			catch(Exception $e){
				$this -> ajaxReturn(array('s' => false));	
			}
		$where1=array('from'=>$toname,'to'=>$name);
		try{
				$res=M('msg')->where($where1)->save($data);
			}
			catch(Exception $e){
				$this -> ajaxReturn(array('s' => false));	
			}
		$this->ajaxReturn(array('s' => true));		
	}
	
}
?>